package com.baozun.houji.goods.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.baozhun.mall.common.adapter.CommonGoodsChannelAdapter
import com.baozhun.mall.common.arouter.RoutePath
import com.baozhun.mall.common.base.BaseActivity
import com.baozhun.mall.common.ext.showToast
import com.baozhun.mall.common.util.CacheUtil
import com.baozhun.mall.common.util.Constants
import com.baozun.houji.goods.R
import com.baozun.houji.goods.adapter.SearchAssociativeListAdapter
import com.baozun.houji.goods.adapter.SearchHistoryAdapter
import com.baozun.houji.goods.databinding.ActivitySearchBinding
import com.baozun.houji.goods.viewmodel.state.SearchViewModel
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.hjq.bar.OnTitleBarListener
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagFlowLayout
import me.hgj.jetpackmvvm.ext.parseState

/**
 * @Title：搜索页
 * @Description：
 * @Author：xing.luo
 * @Since：2022/11/19
 * @Version：1.0.0
 */
class SearchActivity : BaseActivity<SearchViewModel, ActivitySearchBinding>(), OnTitleBarListener, View.OnKeyListener, TagFlowLayout.OnTagClickListener, OnItemClickListener, TextWatcher {

    private val SEARCH_HISTORY_MAX = 10
    var history: MutableList<String> = mutableListOf()

    val recommendListAdapter by lazy { CommonGoodsChannelAdapter(arrayListOf(), onItemClickListener = this) }
    var associativeListAdapter: SearchAssociativeListAdapter? = null

    companion object {
        fun start(context: Context) {
            var intent = Intent(context, SearchActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDataBinding.searchEt.setOnKeyListener(this)
        history = CacheUtil.getSearchHistory()
        mViewModel.historyIsEmpty.value = history.isEmpty()
        mDataBinding.searchHistoryTagFlowLayout.adapter =
            SearchHistoryAdapter(this, history)
        mDataBinding.searchHistoryTagFlowLayout.setOnTagClickListener(this)

//        mViewModel.getSearchRecommend()
//        mDataBinding.searchRecommendLayoutRv.layoutManager = GridLayoutManager(this, 2)
//        mDataBinding.searchRecommendLayoutRv.adapter = recommendListAdapter
//        mDataBinding.searchEt.addTextChangedListener(this)
    }

    override fun createObserver() {
        super.createObserver()

        mViewModel.recommendList.observe(this) { it ->
            parseState(it, {
                recommendListAdapter?.setList(it)
                if (it.isNotEmpty()) {
                    mDataBinding.searchRecommendTv.visibility = View.INVISIBLE
                } else {
                    mDataBinding.searchRecommendTv.visibility = View.INVISIBLE
                }
            }, {
                mDataBinding.searchRecommendTv.visibility = View.INVISIBLE
            })
        }

        mViewModel.associativeList.observe(this) { it ->
            parseState(it, {
                mDataBinding.searchAssociativeLayoutRv.visibility = View.VISIBLE
                initSearchAssociativeList(it)
            }, {})
        }
    }

    private fun initSearchAssociativeList(strings: MutableList<String>) {
        mDataBinding.searchAssociativeLayoutRv.layoutManager = LinearLayoutManager(this)
        associativeListAdapter = SearchAssociativeListAdapter(mDataBinding.searchEt.text.toString(), strings)
        associativeListAdapter?.setOnItemClickListener(this)
        mDataBinding.searchAssociativeLayoutRv.adapter = associativeListAdapter
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.iv_back -> finish()
            R.id.search_history_clear_tv -> clearSearchHistory()
        }
    }

    private fun clearSearchHistory() {
        history.clear()
        CacheUtil.setSearchHistory(history)
        mDataBinding.searchHistoryTagFlowLayout.adapter.notifyDataChanged()
        mViewModel.historyIsEmpty.value = true
    }

    override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_ENTER && event?.action == KeyEvent.ACTION_UP) {
            val keywords: String = mDataBinding.searchEt.text.toString()
            if (keywords.isNotBlank()) {
                search(keywords)
            } else {
                showToast("搜索內容不能為空")
            }
            return true
        } else {
            return false
        }
    }

    private fun search(keywords: String) {
        mDataBinding.searchEt.text = null
        if (history.contains(keywords)) {
            history.remove(keywords)
        }
        history.add(0, keywords)
        if (history.size > SEARCH_HISTORY_MAX) {
            history.removeAt(history.size - 1)
        }
        mViewModel.historyIsEmpty.value = false
        CacheUtil.setSearchHistory(history)
        mDataBinding.searchHistoryTagFlowLayout.adapter.notifyDataChanged()

        ARouter.getInstance().build(RoutePath.Home.SEARCH_RESULT)
            .withString(Constants.Common.BUNDLE_NAME, keywords).navigation()
    }

    override fun onTagClick(view: View?, position: Int, parent: FlowLayout?): Boolean {
        search(history[position])
        return true
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if (view.getTag(com.baozhun.mall.common.R.id.tag_flag_associative) is Boolean) {
            search(associativeListAdapter?.data?.get(position) ?: "")
        }
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

    }

    override fun afterTextChanged(s: Editable?) {
//        if (s.toString().isNotBlank()) {
//            mViewModel.getSearchAssociative(s.toString())
//        } else {
//            mDataBinding.searchAssociativeLayoutRv.visibility = View.GONE
//        }
    }
}